<template>
	<div class="game-container report-container">
		<div class="view-container dealer-container">
			<div class="params">
				<el-form ref="form" :inline="true" :model="queryData">
					<!-- <el-form-item label="存款金额:">
						<el-input
							v-model="queryData.totalDepositAmountMin"
							:controls="false"
							placeholder="最小数值"
							style="width: 100px"
							:maxlength="10"
							name="totalDepositAmountMin"
							@change="vipSerialNumFn"
						></el-input>
						-
						<el-input
							v-model="queryData.totalDepositAmountMax"
							:controls="false"
							placeholder="最大数值"
							:maxlength="10"
							style="width: 100px"
							name="totalDepositAmountMax"
							@change="vipSerialNumFn"
						></el-input>
					</el-form-item> -->
					<el-form-item class="time-options">
						<el-select
							v-model="queryData.queryType"
							:placeholder="$t('common.please_choose')"
							style="width:150px;margin-right: -5px;"
						>
							<el-option
								:label="$t('common.register_time')"
								:value="1"
							></el-option>
							<el-option
								:label="$t('report.first_deposit_time')"
								:value="2"
							></el-option>
							<el-option
								:label="
									$t('friendInvitation.invitee_payout_time1')
								"
								:value="3"
							></el-option>
							<el-option
								:label="
									$t('friendInvitation.invitee_payout_time')
								"
								:value="4"
							></el-option>
						</el-select>

						<el-date-picker
							v-model="searchTime"
							:picker-options="pickerOptions1"
							format="yyyy-MM-dd HH:mm:ss"
							type="datetimerange"
							range-separator="-"
							:start-placeholder="$t('common.start_date')"
							:end-placeholder="$t('common.end_date')"
							align="right"
							:clearable="true"
							:default-time="defaultTime"
							style="width: 375px"
							class="time-options-value"
						></el-date-picker>
					</el-form-item>
					<el-form-item
						:label="
							`${$t('friendInvitation.inviter_account_number')}:`
						"
						prop="inviteUserName"
					>
						<el-input
							v-model="queryData.inviteUserName"
							:placeholder="$t('common.please_enter')"
							:maxlength="500"
							clearable
							style="width: 180px"
						></el-input>
					</el-form-item>
					<el-form-item
						:label="
							`${$t('friendInvitation.inviter_account_number1')}:`
						"
						prop="inviteesUserName"
					>
						<el-input
							v-model="queryData.inviteesUserName"
							:placeholder="$t('common.please_enter')"
							clearable
							:maxlength="500"
							style="width: 180px"
						></el-input>
					</el-form-item>
					<el-form-item
						:label="
							`${$t('friendInvitation.invitee_payout_status')}:`
						"
					>
						<el-select
							v-model="queryData.inviteRewardStatus"
							clearable
							:placeholder="$t('common.select_all')"
							:popper-append-to-body="false"
						>
							<el-option
								:label="$t('common.all')"
								:value="undefined"
							></el-option>
							<el-option
								v-for="item in loginDeviceType"
								:key="item.code"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item
						:label="
							`${$t('friendInvitation.invitee_payout_status1')}:`
						"
					>
						<el-select
							v-model="queryData.inviteesRewardStatus"
							clearable
							:placeholder="$t('common.select_all')"
							:popper-append-to-body="false"
						>
							<el-option
								:label="$t('common.all')"
								:value="undefined"
							></el-option>
							<el-option
								v-for="item in loginDeviceType"
								:key="item.code"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item class="">
						<el-button
							type="primary"
							icon="el-icon-search"
							:disabled="flag"
							@click="search"
						>
							{{ queryText }}
						</el-button>
						<el-button
							icon="el-icon-refresh-left"
							:disabled="resetFlag"
							@click="reset"
						>
							{{ $t('common.reset') }}
						</el-button>
						<el-button
							v-if="hasPermission('90000021')"
							icon="el-icon-download"
							type="warning"
							:disabled="loading"
							@click="exportExcel"
						>
							{{ $t('common.export') }}
						</el-button>
					</el-form-item>
				</el-form>
			</div>
			<div class="content">
				<CommonTable
					ref="hasTotalTable"
					:loading="loading"
					:datas="tableOptions.datas"
					:fieldList="tableOptions.fieldList"
					:operation="tableOptions.operation"
					:summary="tableOptions.summary"
					:pageObj="pageObj"
					:getSummariesObj="tableOptions.getSummariesObj"
					:loadData="loadData"
				></CommonTable>
				<!-- 分页 -->
				<!-- <el-pagination
					class="pageValue"
					:current-page.sync="pageNum"
					background
					layout="total, sizes,prev, pager, next, jumper"
					:page-size="pageSize"
					:page-sizes="[10, 20, 50]"
					:total="total"
					@current-change="handleCurrentChange"
					@size-change="handleSizeChange"
				></el-pagination> -->
			</div>
			<!-- <el-dialog
				title="列设置"
				center
				:visible.sync="dialogShowHide"
				width="500px"
				class="col-setting"
			>
				<div>
					<el-link type="primary" @click="clickDel">复原缺省</el-link>
				</div>
				<div
					v-for="(value, name) in clientProfitAndLoss"
					:key="name"
					class="setting-div"
				>
					<el-checkbox v-model="dialogColumnData[name]">
						{{ name }}
					</el-checkbox>
				</div>
				<div slot="footer" class="dialog-footer">
					<el-button @click="dialogShowHide = false">取 消</el-button>
					<el-button type="primary" @click="updateIndexDB">提交</el-button>
				</div>
			</el-dialog> -->
		</div>
	</div>
</template>

<script>
import list from '@/mixins/list'
import dayjs from 'dayjs'
import { routerNames } from '@/utils/consts'
import CommonTable from '@/components/CommonTable'
const start = dayjs().startOf('day') - 24 * 89 * 60 * 60 * 1000
const end = dayjs()
	.subtract(0, 'day')
	.endOf('day')
export default {
	name: routerNames.clientProfitAndLoss,
	components: {
		CommonTable
	},
	mixins: [list],
	props: {
		merchantInfoObj: {
			type: Object,
			default: () => {}
		}
	},
	data() {
		return {
			queryData: {
				queryType: 1
			},
			searchTime: [start, end],
			day31: 31 * 24 * 3600 * 1000,
			flag: false,
			resetFlag: false,
			queryText: this.$t('common.search'),
			tableData: [],
			dialogList: [],
			pageR: 1,
			sizeR: 10,
			dialogTotal: 0,
			deviceTypeCode: '',
			summary: null,
			title: '',
			visible: false,
			loadingDialog: false,
			//
			clientProfitAndLoss: {
				客户端: true,
				投注人数: true,
				注单量: true,
				投注金额: true,
				有效投注: true,
				投注盈亏: true
			},
			myName: '',
			newList: [],
			timecount: null,
			tableOptions: {
				datas: [],
				fieldList: [
					{
						label: this.$t(
							'friendInvitation.inviter_account_number'
						),
						prop: 'inviteUserName',
						filter: (val) => val || '-',
						show: true
					},
					{
						label: this.$t(
							'friendInvitation.inviter_account_number1'
						),
						prop: 'inviteesUserName',
						filter: (val) => val || '-',
						show: true
					},
					{
						label: this.$t('common.register_time'),
						prop: 'registerAt',
						fit: true,
						width: '160px',
						filter: (val) => val || '-',
						orderColumn: true,
						show: true
					},
					{
						label: this.$t('agent.register_ip'),
						prop: 'registerIp',
						filter: (val) => val || '-',
						show: true
					},
					{
						label: this.$t('risk.terminal_info_register'),
						prop: 'registerDeviceNo',
						filter: (val) => val || '-',
						show: true
					},
					{
						label: this.$t('report.first_deposit_time'),
						prop: 'firstDepositTime',
						orderColumn: true,
						filter: (val) => val || '-',
						show: true
					},
					{
						label: this.$t('agent.first_deposit_mount'),
						prop: 'firstDepositAmount',
						orderColumn: true,
						filter: (val) =>
							this.handleTotalNumber(
								this.merchantInfoObj.currency,
								val
							),
						show: true
					},
					// {
					// 	label: '累计存款金额',
					// 	prop: 'totalDepositAmount',
					// 	orderColumn: true,
					// 	filter: (val) => this.handleTotalNumber(this.merchantInfoObj.currency,val),
					// 	show: true
					// },
					// {
					// 	label: '存款达标金额',
					// 	prop: 'taskDeposit',
					// 	filter: (val) => this.handleTotalNumber(this.merchantInfoObj.currency,val),
					// 	show: true
					// },
					// {
					// 	label: '存款计算方式',
					// 	prop: 'depositCountType',
					// 	filter: (val) => {
					// 		if (val) {
					// 			return {
					// 				1: '首存存款',
					// 				2: '累计存款'
					// 			}[val]
					// 		} else {
					// 			return '-'
					// 		}
					// 	},
					// 	show: true
					// },
					{
						label: this.$t('friendInvitation.tasks_type'),
						prop: 'rewardType',
						filter: (val) => {
							if (val) {
								return {
									1: this.$t(
										'friendInvitation.by_deposit_amount'
									),
									2: this.$t(
										'friendInvitation.by_number_of_invitations'
									)
								}[val]
							} else {
								return '-'
							}
						},
						show: true
					},
					{
						label: this.$t('friendInvitation.invitee_reward'),
						prop: 'inviteRewardAmount',
						orderColumn: true,
						filter: (val) =>
							this.handleTotalNumber(
								this.merchantInfoObj.currency,
								val
							),
						show: true
					},
					{
						label: this.$t('friendInvitation.invitee_payout_time'),
						prop: 'inviteRewardAt',
						orderColumn: true,
						filter: (val) => val || '-',
						show: true
					},
					{
						label: this.$t(
							'friendInvitation.invitee_payout_status'
						),
						prop: 'inviteRewardStatus',
						// orderColumn: true,
						filter: (val) =>
							this.formatInviteRewardStatusValue(val),
						styleCellColor: (val) => this.formatStyle(val),
						show: true
					},
					{
						label: this.$t('friendInvitation.invitee_reward1'),
						prop: 'inviteesRewardAmount',
						orderColumn: true,
						filter: (val) =>
							this.handleTotalNumber(
								this.merchantInfoObj.currency,
								val
							),
						show: true
					},
					{
						label: this.$t('friendInvitation.invitee_payout_time1'),
						prop: 'inviteesRewardAt',
						orderColumn: true,
						filter: (val) => val || '-',
						show: true
					},
					{
						label: this.$t(
							'friendInvitation.invitee_payout_status1'
						),
						prop: 'inviteesRewardStatus',
						filter: (val) =>
							this.formatInviteRewardStatusValue(val),
						styleCellColor: (val) => this.formatStyle(val),
						show: true
					}
				],
				summary: {
					show: true,
					showTotal: false,
					datas: {},
					// 小计
					columns: [
						{
							firstDepositAmount: this.$t(
								'agent.first_deposit_mount'
							),
							key: 'firstDepositAmount',
							filter: (val) =>
								this.handleTotalNumber(
									this.merchantInfoObj.currency,
									val
								)
						},
						// {
						// 	totalDepositAmount: '累计存款金额',
						// 	key: 'totalDepositAmount',
						// 	filter: (val) => this.handleTotalNumber(this.merchantInfoObj.currency,val)
						// },
						{
							inviteRewardAmount: this.$t(
								'friendInvitation.invitee_reward'
							),
							key: 'inviteRewardAmount',
							filter: (val) =>
								this.handleTotalNumber(
									this.merchantInfoObj.currency,
									val
								)
						},
						{
							inviteesRewardAmount: this.$t(
								'friendInvitation.invitee_reward1'
							),
							key: 'inviteesRewardAmount',
							filter: (val) =>
								this.handleTotalNumber(
									this.merchantInfoObj.currency,
									val
								)
						}
					],
					// 总计
					totalColumns: [
						{
							firstDepositAmount: this.$t(
								'agent.first_deposit_mount'
							),
							key: 'totalFirstDepositAmount',
							filter: (val) =>
								this.handleTotalNumber(
									this.merchantInfoObj.currency,
									val
								)
						},
						// {
						// 	totalDepositAmount: '累计存款金额',
						// 	key: 'totalDepositAmount',
						// 	filter: (val) => this.handleTotalNumber(this.merchantInfoObj.currency,val)
						// },

						{
							inviteRewardAmount: this.$t(
								'friendInvitation.invitee_reward'
							),
							key: 'totalInviteRewardAmount',
							filter: (val) =>
								this.handleTotalNumber(
									this.merchantInfoObj.currency,
									val
								)
						},
						{
							inviteesRewardAmount: this.$t(
								'friendInvitation.invitee_reward1'
							),
							key: 'totalInviteesRewardAmount',
							filter: (val) =>
								this.handleTotalNumber(
									this.merchantInfoObj.currency,
									val
								)
						}
					]
				}
			},
			pageObj: {
				show: true,
				pageTotal: 0
			}
		}
	},
	computed: {
		loginDeviceType() {
			// 2)邀请人派奖状态 1.未达标 2.已失效 3.审核中 4.已拒绝 5.待领取 6.已领取 7.已过期
			return [
				{
					code: '1',
					description: this.$t('friendInvitation.not_reached')
				},
				// {
				// 	code: '2',
				// 	description: '已失效'
				// },
				// {
				// 	code: '3',
				// 	description: '审核中'
				// },
				// {
				// 	code: '4',
				// 	description: '已拒绝'
				// },
				{
					code: '5',
					description: this.$t(
						'dict.proxy_water_rebate_status_new.0.description'
					)
				},
				{
					code: '6',
					description: this.$t(
						'dict.proxy_water_rebate_status_new.1.description'
					)
				},
				{
					code: '7',
					description: this.$t(
						'dict.proxy_water_rebate_status_new.2.description'
					)
				}
			]
		}
	},
	watch: {
		tableColumnData: {
			handler(val) {
				this.tableOptions.fieldList.forEach((item) => {
					for (const key in val) {
						if (item.label === key) {
							item.show = val[key]
						}
					}
				})
			},
			// immediate: true,
			deep: true
		}
	},
	mounted() {
		// this.initIndexDB('InvitationData', this.clientProfitAndLoss)
	},
	methods: {
		formatStyle(val) {
			if (val) {
				if (+val === 6) return 'color:green'
				else if (+val === 5) return 'color:#B8741A'
				else if (+val === 7) return 'color:red'
			}
		},
		formatInviteRewardStatusValue(val) {
			if (val) {
				return {
					1: this.$t('friendInvitation.not_reached'),
					// 2: '已失效',
					// 3: '审核中',
					// 4: '已拒绝',
					5: this.$t(
						'dict.proxy_water_rebate_status_new.0.description'
					),
					6: this.$t(
						'dict.proxy_water_rebate_status_new.1.description'
					),
					7: this.$t(
						'dict.proxy_water_rebate_status_new.2.description'
					)
				}[val]
			} else {
				return '-'
			}
		},
		vipSerialNumFn(val) {
			if (val === '') return
			if (
				(+val < +this.queryData.totalDepositAmountMin &&
					this.queryData.totalDepositAmountMin) ||
				(+val > +this.queryData.totalDepositAmountMax &&
					this.queryData.totalDepositAmountMax)
			) {
				// eslint-disable-next-line no-extra-semi
				;[
					this.queryData.totalDepositAmountMin,
					this.queryData.totalDepositAmountMax
				] = [
					this.queryData.totalDepositAmountMax,
					this.queryData.totalDepositAmountMin
				]
			}
		},
		// 列设置
		openSetting() {
			this.getIndexDB(this.clientProfitAndLoss)
			this.dialogShowHide = true
		},
		clickDel() {
			this.dialogColumnData = {}
			this.dialogColumnData = this.clientProfitAndLoss
		},
		loadData(orderParams) {
			if (this.queryData.inviteesRewardStatus === '') {
				delete this.queryData.inviteesRewardStatus
			}
			if (this.queryData.inviteRewardStatus === '') {
				delete this.queryData.inviteRewardStatus
			}

			if (orderParams) {
				const { orderType, orderKey } = orderParams
				// 1-注册时间 2-首存时间 3-首存金额 4-累计存款金额 5-邀请人派奖时间 6-邀请人派奖状态 7-被邀请人派奖时间
				// 排序列：1-注册时间 2-首存时间 3-首存金额 4-累计存款金额 5-邀请人派奖时间 6-邀请人派奖状态 7-被邀请人派奖时间

				const obj = {
					registerAt: 1,
					firstDepositTime: 2,
					firstDepositAmount: 3,
					totalDepositAmount: 4,
					inviteRewardAt: 5,
					inviteRewardStatus: 6,
					inviteesRewardAt: 7,
					inviteRewardAmount: 8,
					inviteesRewardAmount: 9
				}
				this.queryData.orderKey = obj[orderKey]
				this.queryData.orderType = orderType
			}
			const create = this.searchTime || []
			const [startTime, endTime] = create
			const paramsTss = {
				exportFlag: true,
				...this.$refs.hasTotalTable.getParams(),
				queryCondition: {
					...this.queryData,
					merchantId: this.merchantInfoObj.id,
					[this.queryData.name1]: this.queryData.optionsValue,
					startTime:
						(startTime &&
							dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')) ||
						undefined,
					endTime:
						(endTime &&
							dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')) ||
						undefined
				}
			}
			if (this.searchTime?.length === 0) {
				delete paramsTss.queryCondition.queryType
			}
			// if (endTime - startTime >= this.day31) {
			// 	this.$message.warning('请缩小搜索范围至31天')
			// } else {
			this.loading = true
			Promise.all([this.$api.getInviteTaskPageApi(paramsTss)])
				.then(([res]) => {
					if (res.code === 200) {
						this.tableOptions.datas = []
						this.tableData = res?.data?.record || []
						this.pageObj.pageTotal = res?.data?.totalRecord || 0
						this.tableOptions.datas = this.tableData || []
						// this.summary = res2?.data || null
						this.tableOptions.summary.datas = res.data.summary || {}
						this.tableOptions.summary.show = true
						this.tableOptions.summary.showTotal = true
					}
					this.loading = false
				})
				.catch(() => {
					this.loading = false
				})
			// }
		},
		search() {
			this.$refs.hasTotalTable.pageNum = 1
			this.loadData()
		},
		reset() {
			// const S = dayjs()
			// 	.startOf('day')
			// 	.valueOf()
			// const E = dayjs()
			// 	.endOf('day')
			// 	.valueOf()
			this.queryData = { queryType: 1 }
			this.searchTime = [start, end]
			this.$refs.hasTotalTable.pageNum = 1
			this.search()
		},
		exportExcel() {
			const create = this.searchTime || []
			const [startTime, endTime] = create
			const params = {
				exportFlag: true,
				...this.$refs.hasTotalTable.getParams(),
				// queryCondition: {
				...this.queryData,
				merchantId: this.merchantInfoObj.id,
				[this.queryData.name1]: this.queryData.optionsValue,
				startTime:
					(startTime &&
						dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')) ||
					undefined,
				endTime:
					(endTime && dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')) ||
					undefined
				// }
			}
			if (this.searchTime?.length === 0) {
				delete params.queryType
			}
			this.$confirm(
				`<strong>${this.$t(
					'common.is_export'
				)}</strong></br><span style='font-size:12px;color:#c1c1c1'>${this.$t(
					'common.excess_data'
				)}</span>`,
				this.$t('common.success_tip'),
				{
					dangerouslyUseHTMLString: true,
					confirmButtonText: this.$t('common.confirm'),
					cancelButtonText: this.$t('common.cancel'),
					type: 'warning'
				}
			)
				.then(() => {
					this.loading = true
					this.$api
						.getInviteTaskDownloadApi(params)
						.then((res) => {
							this.loading = false
							const { data, status } = res
							if (res && status === 200) {
								const { type } = data
								if (type.includes('application/json')) {
									const reader = new FileReader()
									reader.onload = (evt) => {
										if (evt.target.readyState === 2) {
											const {
												target: { result }
											} = evt
											const ret = JSON.parse(result)
											if (ret.code !== 200) {
												this.$message({
													type: 'error',
													message: ret.msg,
													duration: 1500
												})
											}
										}
									}
									reader.readAsText(data)
								} else {
									const result = res.data
									const disposition =
										res.headers['content-disposition']
									const fileNames =
										disposition && disposition.split("''")
									let fileName = fileNames[1]
									fileName = decodeURIComponent(fileName)
									const blob = new Blob([result], {
										type: 'application/octet-stream'
									})
									if (
										'download' in
										document.createElement('a')
									) {
										const downloadLink = document.createElement(
											'a'
										)
										downloadLink.download = fileName || ''
										downloadLink.style.display = 'none'
										downloadLink.href = URL.createObjectURL(
											blob
										)
										document.body.appendChild(downloadLink)
										downloadLink.click()
										URL.revokeObjectURL(downloadLink.href)
										document.body.removeChild(downloadLink)
									} else {
										window.navigator.msSaveBlob(
											blob,
											fileName
										)
									}
									this.$message({
										type: 'success',
										message: this.$t(
											'common.export_success'
										),
										duration: 1500
									})
								}
							}
						})
						.catch(() => {
							this.loading = false
							// this.$message({
							// 	type: 'error',
							// 	message: '导出失败',
							// 	duration: 1500
							// })
						})
				})
				.catch(() => {
					this.loading = false
				})
		}
	}
}
</script>

<style lang="scss" scoped>
.chechox {
	display: flex;
	flex-direction: column;
	height: 400px;
	overflow-y: auto;
}
::v-deep .el-dialog__header {
	color: #5c5c5c;
	font-weight: 700;
}
.count_row {
	height: 80px;
	color: #5c5c5c;
	p {
		height: 40px;
		line-height: 40px;
		font-weight: 700;

		span {
			display: inline-block;
			width: 20px;
			height: 20px;
		}
	}
}
.fenye {
	text-align: center;
}
::v-deep .el-input__inner {
	padding: 1px 10px;
}
.setting-div {
	display: inline-block;
	min-width: 90px;
}
</style>
